package com.example.myapplication10.Activities;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication10.Buttons.Btn_Search;
import com.example.myapplication10.Buttons.Btn_history;
import com.example.myapplication10.MsgEvents.MsgEventAddCity;
import com.example.myapplication10.MsgEvents.MsgEventAddIntent;
import com.example.myapplication10.MsgEvents.MsgEventException;
import com.example.myapplication10.MsgEvents.MsgEventRemoveIntent;
import com.example.myapplication10.R;
import com.hxc.basemodule.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class AddActivity extends BaseActivity {
    RecycleAdapter adapter = new RecycleAdapter();
    int code = 1;
    int size = 1;
    boolean isFirstSearch = true;
    boolean delFlag = false;
    JSONArray jsonArray = new JSONArray();
    Map<String, ?> map;
    String search = "";
    String res = null;
    EditText searchView;
    Btn_Search btn_search;
//    Btn_history btnHistory = findViewById()
    List<String> resCities = new ArrayList<>();
    List<Map<String,String>> initCitiesAndCodes = new ArrayList<>();
    List<Map<String,String>> resCitiesAndCodes = new ArrayList<>();
    LinearLayout layoutA;LinearLayout layoutB;LinearLayout layoutC;

    public String getCityString(int rawResId){
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //得到资源中的Raw数据流
            inputStream = getResources().openRawResource(rawResId);
            reader = new InputStreamReader(inputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("getCityString", "result:" + result);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void setHistoryView(int size) {
        if (size<=1){
            layoutA.setVisibility(View.GONE);
            layoutB.setVisibility(View.GONE);
            layoutC.setVisibility(View.GONE);
        }
        else if (size<=5){
            layoutA.setVisibility(View.VISIBLE);
            layoutB.setVisibility(View.GONE);
            layoutC.setVisibility(View.GONE);
        }
        else if (size<=10){
            layoutA.setVisibility(View.VISIBLE);
            layoutB.setVisibility(View.VISIBLE);
            layoutC.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        showBackButton();
        EventBus.getDefault().register(this);
        setImmersiveWindows();
        RecyclerView recyclerView = findViewById(R.id.recycleView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));
        layoutA = findViewById(R.id.historyA);
        layoutB = findViewById(R.id.historyB);
        layoutC = findViewById(R.id.historyC);
        map = new HashMap<>();
        Map<String,String> map0 = new HashMap<>();
        SharedPreferences sharedPreferences
                = getSharedPreferences("search_history",MODE_PRIVATE);
        map = sharedPreferences.getAll();
        this.size = map.size();

        setHistoryView(this.size);

        searchView = findViewById(R.id.search_text);
        search = getCityString(R.raw.city);
        setTitle("城市管理");


        Intent intent = getIntent();
        layoutA = findViewById(R.id.historyA);
        layoutB = findViewById(R.id.historyB);
        layoutC = findViewById(R.id.historyC);
        String addedCities = intent.getStringExtra("addedCities");

        JSONObject jsonObject = JSONObject.parseObject(search);
        this.jsonArray = jsonObject.getJSONArray("城市");
        btn_search = findViewById(R.id.btn_search);
        if (!map.isEmpty()){
            for (Map.Entry<String,?> entry : map.entrySet()){
                map0 = new HashMap<>();
                map0.put("城市名称", entry.getKey());
                map0.put("城市代码", entry.getValue().toString());
                this.initCitiesAndCodes.add(map0);
            }
        }
        if (map.size()>=16){
            searchView.setVisibility(View.GONE);
            btn_search.setVisibility(View.GONE);
            code = 0;
            showAlertDialog("提示","最多可添加15个城市");
        }
        else if(map.entrySet().isEmpty()){
            showAlertDialog("警告","没有设置初始城市，请联系开发人员");
            finish();
        }
        else{
            searchView.setVisibility(View.VISIBLE);
            btn_search.setVisibility(View.VISIBLE);
        }
        int i = 0;
        if (!initCitiesAndCodes.isEmpty()) {
            recyclerView.setAdapter(adapter);
            for (Map<String, String> map1 : initCitiesAndCodes) {
                if(i >= 15){
                    break;
                }
                Btn_history btnHistory = findViewById(findButtonId(i));
                btnHistory.updateHistory(map1.get("城市名称"));
                btnHistory.setOnClickListener(new View.OnClickListener() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onClick(View v) {
                        adapter.setDelFlag(true);
                        if (adapter.isDelFlag() != delFlag){
                            resCitiesAndCodes.clear();
                        }
                        if (!resCitiesAndCodes.contains(map1)) {
                            resCitiesAndCodes.clear();
                            resCitiesAndCodes.add(map1);
                        }
                        adapter.setData(resCitiesAndCodes, size);
                        delFlag = true;
                        adapter.notifyDataSetChanged();
                    }
                });
                i++;
            }
        }





//        if (Objects.equals(addedCities, "reset") || size <= 2){
////            code = 0;
//        }
//        else {
////            code = 1;
//            search = search.replace(addedCities, "");
//        }


        btn_search.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                search = searchView.getText().toString();
                Map<String,String> map = new HashMap<>();
                adapter.setDelFlag(false);
                recyclerView.setAdapter(adapter);
                if(!Objects.equals(search, "")) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        String res0 = object.getString(search);
                        if (res0 != null) {
                            res = res0;
                            resCities.add(res);
                        }
                    }
                    adapter.setDelFlag(false);
                    if (adapter.isDelFlag() != delFlag){
                        resCitiesAndCodes.clear();
                    }
                    if (isFirstSearch) {
                        if (!resCities.isEmpty()) {
                            for (int i = 0; i < resCities.size(); i++) {
                                map = new HashMap<>();
                                map.put("城市名称", search);
                                map.put("城市代码", resCities.get(i));
                                resCitiesAndCodes.add(map);
                            }
                            resCities.clear();
                            adapter.setData(resCitiesAndCodes, size);
                            adapter.notifyDataSetChanged();
                            searchView.setText("");
//                        setResult(1, intentBack);
                        } else {
                            showAlertDialog("提示","未找到结果");
//                        setResult(0, intentBack);
                        }
                        isFirstSearch = false;
                    }
                    else {
                        if (!resCities.isEmpty()) {
                            for (int i = 0; i < resCities.size(); i++) {
                                map = new HashMap<>();
                                map.put("城市名称", search);
                                map.put("城市代码", resCities.get(i));
                                resCitiesAndCodes.add(map);
                            }
                            resCities.clear();
                            adapter.setData(resCitiesAndCodes, size);
                            adapter.notifyDataSetChanged();
                            searchView.setText("");
//                        setResult(1, intentBack);
                        } else {
                            showAlertDialog("提示","未找到结果");
//                        setResult(0, intentBack);
                        }
                    }
                    delFlag = false;
                }
            }
        });
        Intent intentBack = new Intent(AddActivity.this, MainActivity.class);
        setResult(-2,intentBack);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventAddCity(MsgEventAddCity event) {
        Map<String, String> map = event.getMsg();

        Btn_history btnHistory = findViewById(findButtonId(this.size));
        btnHistory.updateHistory(map.get("城市名称"));
        this.size += 1;
        setHistoryView(this.size);

//        if (code == 0 || code == -1) {
        Intent intentBack = new Intent(AddActivity.this, MainActivity.class);
        SharedPreferences sharedPreferences
                = getSharedPreferences("search_history", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        this.map = sharedPreferences.getAll();
        boolean flag = true;
        showProgressDialog("极简天气","添加中......");
            for (Map.Entry<String,?> entry : this.map.entrySet()){
                if (Objects.equals(entry.getKey(), map.get("城市名称"))){
                    flag = false;
//                        SharedPreferences.Editor editor0 = sharedPreferences.edit();
//                        editor0.remove(map.get("城市名称"));
//                        editor0.apply();
                    break;
                }
            }
            if(flag) {
                editor.putString(map.get("城市名称"), map.get("城市代码"));
                editor.apply();
            }
        if(flag) {

        }

        setResult(1, intentBack);
    }
//            if (code == -1) {
//                EventBus.getDefault().post(new MsgEventResumeCity(list));
//            }
//        }
//        if (code == 0){
//            setResult(1, intentBack);
//        }
//        else if(code == -1){
////            EventBus.getDefault().post(new MsgEventResumeCity(list));
//            setResult(-2,intentBack);
//        }
//        else{

//        }
//        for (Map<String,String> map : list){
//            if (!addCityList.contains(map) && !cityList.contains(map)){
//                this.addCityList.add(map);
//            }
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventException(MsgEventException event) {
        String e = event.getException();
        showAlertDialog("错误", e, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intentE = new Intent(AddActivity.this, MainActivity.class);
                if(e.contains("此城市已添加，不能重复添加！")) {
                    setResult(0, intentE);
                    finish();
                }
                else if(e.contains("最多可同时添加15个城市")){
                    searchView.setVisibility(View.GONE);
                    btn_search.setVisibility(View.GONE);
                }
                else {
                    setResult(-1, intentE);
                    finish();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBusAddIntent(MsgEventAddIntent event) {
//        Toast.makeText(this, event.msg + " 添加成功", Toast.LENGTH_SHORT).show();
        hideProgressDialog();
//        Intent intentBack = new Intent(AddActivity.this, MainActivity.class);
//        if (code == 0) {
//            setResult(1, intentBack);
//        } else if (code == -1) {
//            setResult(-2, intentBack);
//        } else {
//            setResult(1, intentBack);
//        }
    }
//        if (code == 0 || code == -1) {
//
//            SharedPreferences sharedPreferences
//                    = getSharedPreferences("search_history", MODE_PRIVATE);
//            SharedPreferences.Editor editor = sharedPreferences.edit();
//            if (list.size() < 15 && list.size() != 0) {
//                for (Map<String, String> map : list) {
//                    editor.putString(map.get("城市名称"), map.get("城市代码"));
//                }
//                editor.apply();
//            }
//            if (code == -1) {
//                EventBus.getDefault().post(new MsgEventResumeCity(list));
//            }
//        }
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void messageEventRemoveCity(MsgEventRemoveCity event) {
//        List<Map<String,String>> list = event.getMsg();
////        if (this.code == -1) {
////            EventBus.getDefault().post(new MsgEventRemoveIntent(list));
////        }
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBusRemoveIntent(MsgEventRemoveIntent event) {
        SharedPreferences sharedPreferences
                = getSharedPreferences("search_history",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Map<String,String> map = event.getMsg();
        for (int i = 0; i < initCitiesAndCodes.size(); i++) {
            Btn_history btnHistory = findViewById(findButtonId(i));
            if(Objects.equals(btnHistory.getStr(), map.get("城市名称"))){
                btnHistory.setVisibility(View.INVISIBLE);
            }
        }
//        int size = sharedPreferences.getAll().size();
        editor.remove(map.get("城市名称"));
        editor.apply();
        Intent intentBack = new Intent(AddActivity.this, MainActivity.class);
        if (this.code == 0){
            setResult(-1, intentBack);
        }
//        else if(code == -1){
//            setResult(-2,intentBack);
//        }
        else {
            setResult(0, intentBack);
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void messageEventAddCity(MsgEventAddCity event) {
//        EventBus.getDefault().post(new MsgEventAddCity(event.getMsg()));
////        weatherFragmentAdapter.addCityList.addAll(event.getMsg());
//    }
    public int findButtonId(int index){
        switch (index){
            case 0:
                return R.id.history1;
            case 1:
                return R.id.history2;
            case 2:
                return R.id.history3;
            case 3:
                return R.id.history4;
            case 4:
                return R.id.history5;
            case 5:
                return R.id.history6;
            case 6:
                return R.id.history7;
            case 7:
                return R.id.history8;
            case 8:
                return R.id.history9;
            case 9:
                return R.id.history10;
            case 10:
                return R.id.history11;
            case 11:
                return R.id.history12;
            case 12:
                return R.id.history13;
            case 13:
                return R.id.history14;
            case 14:
                return R.id.history15;
            default:
                return 0;
        }
    }
    @Override
    protected int setCurrentLayoutId() {
        return R.layout.activity_add;
    }
}